const { accessTokenExpired } = require('./utils')
const services = require('./services')
const codeStore = {}

let webAccessTokenStore = null
function saveWebAccessTokenStore(store, code) {
  codeStore[code] = webAccessTokenStore = Object.assign({}, store, {
    expires_in: ~~(new Date().getTime() / 1000) + store.expires_in /* seconds */
  })
}

// Notes:
// server Reload, can't make sure access_token is valid
// access_token expire_in 7200 for now
function getWebAccessToken(appid, secret, code) {
  // Try best to reduce http
  /*if (!accessTokenExpired(webAccessTokenStore)) {
    return Promise.resolve(webAccessTokenStore)
  }*/

  // access_token expired, but refresh_token( 30 days) Exists.
  /*if (webAccessTokenStore && webAccessTokenStore.refresh_token) {
    return services.refreshWebAccessToken(config.appid, webAccessTokenStore.refresh_token)
      .then(response => {
        saveWebAccessTokenStore(response)
        return response
      })
  }
*/
  // get access_token,
  // but can't be sure that access_token is valid, need to refresh.
  return Promise.resolve()
    .then( _ =>
      codeStore[code]
      ? codeStore[code]
      : services.getWebAccessToken(appid, secret, code))
    .then(response => {
      const { errcode, errmsg } = response;
      if (errcode && errmsg) {
        throw new Error(errmsg)
      }

      console.log('getWebAccessToken')
      console.log(response)

      saveWebAccessTokenStore(response, code)
      return response
    })
    .then(response => {
      console.log('查看是否有效？？')
      // Make sure that access_token is valid.
      const { access_token, openid } = response
      return services.webAccessTokenValid(access_token, openid)
        .then(() => {
          saveWebAccessTokenStore(response, code)
          console.log('有效', response)
          return response
        })
        .catch(() => {
          console.log('无效刷新', response)
          return services.refreshWebAccessToken(config.appid, response.refresh_token)
                  .then(response => {
                    saveWebAccessTokenStore(response, code)
                    return response
                  })
        })
    })
}

module.exports = {
  webAccessTokenStore: webAccessTokenStore,
  saveWebAccessTokenStore: saveWebAccessTokenStore,
  getWebAccessToken: getWebAccessToken
}
